//
//  ProductsDetailViewController.m
//  Jingjing
//
//  Created by user on 15/11/12.
//  Copyright © 2015年 Mikeshihua. All rights reserved.
//

#import "ProductsDetailViewController.h"
#import "OfflineSalonCell.h"
#import "LoginViewController.h"

#import "DetailActivity.h"
#import "ProductsDetailsInsidePagesViewController.h"
@interface ProductsDetailViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)UITableView * ProducteDetailTabelView;
@property (nonatomic,strong)UIView      * upView;
@property (nonatomic,strong)UIView      * midleView;
@property (nonatomic,strong)UIView      * downView;


@property(nonatomic,strong)  NSMutableArray *dataSourceArr;

@property (nonatomic, assign)int idx;
@property (nonatomic,assign) int n;

@property (strong, nonatomic)UIView *noDataView;
@property(nonatomic,strong)UIView *noNet;

@end

@implementation ProductsDetailViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    
    TopView *topView = [[TopView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:self.navTitle];
    [self.view addSubview:topView];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton * backBtn = [[UIButton alloc]initWithFrame:CGRectMake(10.0f, 20.0f, 44.0f, 44.0f)];
    [backBtn setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnCLick:) forControlEvents:UIControlEventTouchUpInside];
    backBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [topView addSubview:backBtn];
    
    
   _ProducteDetailTabelView = [[UITableView alloc] initWithFrame:CGRectMake(16.0f ,64.0f,SCREEN_WIDTH-32.0f ,SCREEN_HEIGHT-64.0f) style:UITableViewStyleGrouped];
   _ProducteDetailTabelView.backgroundColor = [UIColor clearColor];
    _ProducteDetailTabelView.showsVerticalScrollIndicator = NO;
   _ProducteDetailTabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _ProducteDetailTabelView.delegate = self;
    _ProducteDetailTabelView.dataSource = self;
    _ProducteDetailTabelView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTheTableView)];
       [self.view addSubview:self.ProducteDetailTabelView];
    [_ProducteDetailTabelView addSubview:self.noDataView];
    [_ProducteDetailTabelView addSubview:self.noNet];
   
}
- (void)viewWillAppear:(BOOL)animated
{
    [_ProducteDetailTabelView.header beginRefreshing];

}

- (void)backBtnCLick:(UIButton*)btn
{
    [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    [self.navigationController popViewControllerAnimated:YES];
}
//没网提示
#pragma mark - 没网提示
-(UIView *)noNet
{
    if (!_noNet) {
        _noNet = [[UIView alloc]initWithFrame:CGRectMake((_ProducteDetailTabelView.frame.size.width-200)/2, (_ProducteDetailTabelView.frame.size.height-200)/2, 200, 235)];
        _noNet.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(45, 23, 110, 110);
        [button setImage:[UIImage imageNamed:@"img_nonetwork"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 44, 200, 44)];
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        NSMutableAttributedString *aString = [[NSMutableAttributedString alloc]initWithString:@"加载失败\n请检查手机是否联网"];
        
        [aString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17],
                                 NSForegroundColorAttributeName:[UIColor colorWithWhite:0.098 alpha:1.000],
                                 } range:NSMakeRange(0, 5)];
        
        [aString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12],
                                 NSForegroundColorAttributeName:[UIColor colorWithWhite:0.702 alpha:1.000],
                                 } range:NSMakeRange(5, 9)];
        [label setAttributedText:aString];
        [_noNet addSubview:label];
        [_noNet addSubview:button];
        
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(60, 210, 80, 25);
        btn.backgroundColor = [UIColor colorWithWhite:0.200 alpha:1.000];
        btn.layer.cornerRadius = 6;
        btn.layer.masksToBounds = YES;
        [btn setTitle:@"重新加载" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_noNet addSubview:btn];
        
    }
    
    return _noNet;
}

-(UIView *)noDataView{
    if (!_noDataView) {
        
        _noDataView = [[UIView alloc]initWithFrame:CGRectMake((_ProducteDetailTabelView.frame.size.width-200)/2, (_ProducteDetailTabelView.frame.size.height-200)/2, 200, 235)];
        _noDataView.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(45, 45, 110, 110);
        [button setImage:[UIImage imageNamed:@"img_nodata"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 44, 200, 44)];
        label.text = @"暂无数据";
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        label.font = [UIFont systemFontOfSize:14.0f];
        label.textColor = [UIColor colorWithWhite:0.000 alpha:0.540];
        [_noDataView addSubview:label];
        [_noDataView addSubview:button];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(60, 210, 80, 25);
        btn.backgroundColor = [UIColor colorWithWhite:0.200 alpha:1.000];
        btn.layer.cornerRadius = 6;
        btn.layer.masksToBounds = YES;
        [btn setTitle:@"点击返回" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(backBtnCLick:) forControlEvents:UIControlEventTouchUpInside];
        [_noDataView addSubview:btn];
        
    }
    
    return _noDataView;
}

- (void)noResultButtonAction:(id)sender
{
    [self refreshTheTableView];
}
-(void)refreshTheTableView
{
    _idx = 0;
    _n = 0;
    
    [self httpRequest];
}

- (void)AddtoTheProjectTableView
{
    [self httpRequest];
}

- (void)httpRequest
{
   
    _noNet.hidden = TRUE;
    _noDataView.hidden = TRUE;
    
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray array];
    }
    _n++;
    

    
    NSDictionary *dict = @{ @"page.size":[NSNumber numberWithInt:10],@"page.pn":[NSNumber numberWithInt:_idx + 1],@"activitiesTypeId":self.activitesTypeId,@"token":[[NSUserDefaults standardUserDefaults]objectForKey:@"token"]?[[NSUserDefaults standardUserDefaults]objectForKey:@"token"]:@""};
    
    
    [AppGlobalClass PostDataWithNSstring:GETACTIVITIESLIST withDictionary:dict success:^(NSDictionary *dictionary) {
        
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            
            [self.ProducteDetailTabelView.header endRefreshing];
            [self.ProducteDetailTabelView.footer setState:MJRefreshStateIdle];
            [self.ProducteDetailTabelView.footer endRefreshing];
            
            
            if(_idx == 0)
            {
                [_dataSourceArr removeAllObjects];
                
            }
            
            
            if ([[[[dictionary objectForKey:@"responseData"] firstObject]objectForKey:@"pages"]intValue]>_idx) {
                
                NSArray * dataArray = [[[dictionary objectForKey:@"responseData"] firstObject]objectForKey:@"rows"];
                self.ProducteDetailTabelView.tableHeaderView.hidden = FALSE;
                
                
                for (NSDictionary *dataDic in dataArray) {
                    
                    DetailActivity *aDetailActivity = [[DetailActivity alloc]initWithDictionary:dataDic];
                    [_dataSourceArr addObject:aDetailActivity];
                    
                    
                }
                
                _idx++;
                
                [self.ProducteDetailTabelView reloadData];
                
                if (self.dataSourceArr.count==0) {
                    
                     _noDataView.hidden = FALSE;
                    _ProducteDetailTabelView.tableHeaderView.hidden = TRUE;
                }
                
                else if(self.dataSourceArr.count < 10){
                    [self.ProducteDetailTabelView.footer endRefreshingWithNoMoreData];
                    _ProducteDetailTabelView.tableHeaderView.hidden = FALSE;
                   
                    
                }
                else{
                    _ProducteDetailTabelView.tableHeaderView.hidden = FALSE;
                    
                    
                    if (_n<2) {
                        self.ProducteDetailTabelView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(AddtoTheProjectTableView)];
                        
                    }
                }
                
            }
            else
            {
                if (self.dataSourceArr.count == 0) {
                    self.ProducteDetailTabelView.tableHeaderView.hidden = TRUE;
                   
                    _noDataView.hidden = FALSE;
                    
                }
                [self.ProducteDetailTabelView.footer endRefreshingWithNoMoreData];
                
            }
        }else{
            NSString * str = [dictionary objectForKey:@"message"];
            ALERT_VIEW(str);
            
            _ProducteDetailTabelView.tableHeaderView.hidden = TRUE;
            
            [self.ProducteDetailTabelView.header endRefreshing];
            
        }

    } failure:^(NSError *error) {
        _noDataView.hidden = FALSE;
       
        [_dataSourceArr removeAllObjects];
        [_ProducteDetailTabelView reloadData];
        _ProducteDetailTabelView.tableHeaderView.hidden = TRUE;
        [self.ProducteDetailTabelView.header endRefreshing];
        [self.ProducteDetailTabelView.footer setState:MJRefreshStateIdle];
        [self.ProducteDetailTabelView.footer endRefreshing];
    } networkerror:^(NSString *networkerror) {
        _noNet.hidden = FALSE;
        
        _ProducteDetailTabelView.tableHeaderView.hidden = TRUE;
        
        [self.ProducteDetailTabelView.header endRefreshing];
        [self.ProducteDetailTabelView.footer setState:MJRefreshStateIdle];
        [self.ProducteDetailTabelView.footer endRefreshing];
        [self.dataSourceArr removeAllObjects];
        [_ProducteDetailTabelView reloadData];
        
        
    }];
    
    
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataSourceArr.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    OfflineSalonCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[OfflineSalonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    
    DetailActivity *aDeatilActigity = [_dataSourceArr objectAtIndex:indexPath.section];
    cell.titleLabel.text = aDeatilActigity.title;

    NSString *valid = [NSString stringWithFormat:@"%@",aDeatilActigity.valid];
    if ([valid isEqualToString:@"0"]) {
        //不可报名
        cell.WhetherYToSignUpImgView.hidden = YES;
        
        
    }else if ([valid isEqualToString:@"1"]){
        //可以报名
         cell.WhetherYToSignUpImgView.hidden = NO;
        cell.WhetherYToSignUpImgView.image = [UIImage imageNamed:@"icon_sign"];
    }else{
        //已报名
         cell.WhetherYToSignUpImgView.hidden = NO;
         cell.WhetherYToSignUpImgView.image = [UIImage imageNamed:@"icon_sign_ok"];
        
    }
    
    
    [cell.imgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",RESOURCE_URL,aDeatilActigity.imgUrl]] placeholderImage:[UIImage imageNamed:@"img_default2"]];
   
   
    
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 257.0f;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    DetailActivity *model = [_dataSourceArr objectAtIndex:indexPath.section];
     NSString *valid = [NSString stringWithFormat:@"%@",model.valid];
    ProductsDetailsInsidePagesViewController *productDetailInsidePagesVC = [[ProductsDetailsInsidePagesViewController alloc]init];
    productDetailInsidePagesVC.navTitle = model.title;
   
    productDetailInsidePagesVC.activitesTypeId = model.activitiesId;
    productDetailInsidePagesVC.valid = valid;
    NSLog(@"====%@",valid);
    [self.navigationController pushViewController:productDetailInsidePagesVC animated:YES];
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 0;
    }
    return 16.0f;
}
//-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
//{
//    return 8.0f;
//}
//-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//    UIView * backview = [[UIView alloc]init];
//    backview.backgroundColor = [UIColor hexStringToColor:@"#f3f3f3"];
//    return backview;
//}



@end
